<template>
  <div class="customer-insight">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>客户消费频次分析</span>
              <el-button type="primary" size="small" @click="refreshData">刷新数据</el-button>
            </div>
          </template>
          <div ref="consumptionFrequency" class="chart-container frequency-chart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>客户年龄分布</span>
              <el-button type="primary" size="small" @click="refreshData">刷新数据</el-button>
            </div>
          </template>
          <div ref="ageDistribution" class="chart-container age-chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { CustomerInsightConfig } from './CustomerInsight/config.js'
import './CustomerInsight/style.css'
import chartManager from '../utils/ChartManager.js'

// 图表引用
const consumptionFrequency = ref(null)
const ageDistribution = ref(null)

// 配置
const config = CustomerInsightConfig

// 初始化客户消费频次分析
const initConsumptionFrequency = () => {
  console.log('初始化消费频次图表，ref:', consumptionFrequency.value)
  if (!consumptionFrequency.value) {
    console.error('消费频次图表容器未找到')
    return
  }

  // 检查容器尺寸
  const container = consumptionFrequency.value
  console.log('容器原始尺寸:', container.offsetWidth, 'x', container.offsetHeight)

  // 如果容器尺寸为0，等待下一帧
  if (container.offsetWidth === 0 || container.offsetHeight === 0) {
    console.log('容器尺寸为0，等待下一帧...')
    requestAnimationFrame(() => {
      initConsumptionFrequency()
    })
    return
  }

  // 设置固定的正常宽度和高度
  container.style.height = '450px'
  container.style.width = '100%'
  container.style.minHeight = '450px'
  container.style.minWidth = '400px'
  container.style.display = 'block'
  container.style.visibility = 'visible'
  container.style.overflow = 'hidden'

  // 等待样式应用
  setTimeout(() => {
    console.log('样式应用后容器尺寸:', container.offsetWidth, 'x', container.offsetHeight)

    const chart = echarts.init(container)

    // 保存图表引用到容器
    container._echarts = chart
    container._chartOption = null // 用于存储图表选项

    const option = {
      title: {
        text: '客户消费频次分布',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
          color: '#303133'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: '5%',
        top: 'middle',
        data: ['高频客户(>10次)', '中频客户(5-10次)', '低频客户(2-5次)', '新客户(1次)'],
        textStyle: { fontSize: 12 }
      },
      series: [
        {
          name: '消费频次',
          type: 'pie',
          radius: ['30%', '60%'],
          center: ['60%', '50%'],
          avoidLabelOverlap: false,
          label: { show: false, position: 'center' },
          emphasis: {
            label: {
              show: true,
              fontSize: 18,
              fontWeight: 'bold'
            }
          },
          labelLine: { show: false },
          data: [
            { value: 335, name: '高频客户(>10次)', itemStyle: { color: '#c23531' } },
            { value: 310, name: '中频客户(5-10次)', itemStyle: { color: '#2f4554' } },
            { value: 234, name: '低频客户(2-5次)', itemStyle: { color: '#61a0a8' } },
            { value: 135, name: '新客户(1次)', itemStyle: { color: '#d48265' } }
          ]
        }
      ]
    }

    // 保存选项到容器
    container._chartOption = option

    console.log('设置消费频次图表选项:', option)
    chart.setOption(option)

    // 注册到图表管理器
    chartManager.registerChart('consumptionFrequency', chart, container)

    console.log('消费频次图表初始化完成，固定尺寸模式')
  }, 50)
}

// 初始化客户年龄分布
const initAgeDistribution = () => {
  console.log('初始化年龄分布图表，ref:', ageDistribution.value)
  if (!ageDistribution.value) {
    console.error('年龄分布图表容器未找到')
    return
  }

  // 检查容器尺寸
  const container = ageDistribution.value
  console.log('容器原始尺寸:', container.offsetWidth, 'x', container.offsetHeight)

  // 如果容器尺寸为0，等待下一帧
  if (container.offsetWidth === 0 || container.offsetHeight === 0) {
    console.log('容器尺寸为0，等待下一帧...')
    requestAnimationFrame(() => {
      initAgeDistribution()
    })
    return
  }

  // 设置固定的正常宽度和高度
  container.style.height = '450px'
  container.style.width = '100%'
  container.style.minHeight = '450px'
  container.style.minWidth = '400px'
  container.style.display = 'block'
  container.style.visibility = 'visible'
  container.style.overflow = 'hidden'

  // 等待样式应用
  setTimeout(() => {
    console.log('样式应用后容器尺寸:', container.offsetWidth, 'x', container.offsetHeight)

    const chart = echarts.init(container)

    // 保存图表引用到容器
    container._echarts = chart
    container._chartOption = null // 用于存储图表选项

    const option = {
      title: {
        text: '客户年龄分布',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
          color: '#303133'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' }
      },
      grid: {
        left: '10%',
        right: '10%',
        bottom: '20%',
        top: '20%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['18-25岁', '26-35岁', '36-45岁', '46-55岁', '56-65岁', '65岁以上'],
        axisLabel: {
          fontSize: 12,
          interval: 0,
          margin: 10
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value}人',
          fontSize: 11
        }
      },
      series: [
        {
          name: '客户数量',
          type: 'bar',
          data: [120, 200, 150, 80, 70, 110],
          itemStyle: {
            color: function (params) {
              const colors = ['#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452']
              return colors[params.dataIndex]
            }
          },
          barWidth: '50%',
          label: {
            show: true,
            position: 'top',
            fontSize: 12
          }
        }
      ]
    }

    // 保存选项到容器
    container._chartOption = option

    console.log('设置年龄分布图表选项:', option)
    chart.setOption(option)

    // 注册到图表管理器
    chartManager.registerChart('ageDistribution', chart, container)

    console.log('年龄分布图表初始化完成，固定尺寸模式')
  }, 50)
}

// 刷新数据
const refreshData = () => {
  ElMessage.success('数据已刷新')
  // 这里可以添加实际的数据刷新逻辑
}

// 组件挂载时初始化图表
onMounted(() => {
  console.log('组件已挂载，开始初始化图表...')

  // 等待DOM渲染完成
  nextTick(() => {
    console.log('DOM渲染完成，初始化所有图表...')

    // 检查容器状态
    console.log('消费频次容器:', consumptionFrequency.value)
    console.log('年龄分布容器:', ageDistribution.value)

    // 初始化所有图表
    initConsumptionFrequency()
    initAgeDistribution()

    console.log('所有图表初始化完成')
  })
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>